<template>
  <div>
    <!--  面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--  卡片视图区域  -->
    <el-card style="text-align: left">
      <!--  按钮区域 添加角色 -->
      <el-button type="primary" @click="addDialogVisible = true">添加角色</el-button>
      <!--  角色列表数据区域  -->
      <el-table :data="rolesList" stripe border>
        <!--  为表格添加展开列  -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!--  第一层for循环-->
            <el-row :class="['bdb',i1 == 0 ?'bdt':'','center']" v-for="(item1,i1) in scope.row.children"
                    :key="item1.id">
              <!--  第一级权限-->
              <el-col :span="5">
                <el-tag @close="deleteById(scope.row,item1.id)" closable>{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!--  第二级权限 第三级权限 -->
              <el-col :span="19">
                <!--  第二层for循环-->
                <el-row :class="[i2 == 0 ?'':'bdt','center']" v-for="(item2,i2) in item1.children" :key="item2.id">
                  <!--  第二级权限 -->
                  <el-col :span="5">
                    <el-tag @close="deleteById(scope.row,item2.id)" closable type="success">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="19">
                    <!--  第三级权限 -->
                    <el-tag closable @close="deleteById(scope.row,item3.id)" type="warning"
                            v-for="(item3) in item2.children" :key="item3.id">
                      {{item3.authName}}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!--为表格添加索引列  -->
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="roleName" label="角色名称" width="380"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述" width="380"></el-table-column>
        <el-table-column prop="address" label="操作">
          <!-- 接收这一行的数据  -->
          <template slot-scope="scope">
            <!--  编辑  -->
            <el-button @click="alterRole(scope.row.id)" type="primary" icon="el-icon-edit" size="mini"></el-button>
            <!--  删除  -->
            <el-button @click="deleteRole(scope.row.id)" type="danger" icon="el-icon-delete" size="mini"></el-button>
            <!--  分配权限  -->
            <el-tooltip class="item" effect="dark" content="分配权限" :enterable="false" placement="top">
              <el-button @click="showSetting(scope.row)" type="warning" icon="el-icon-setting" size="mini"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色的对话框  -->
    <el-dialog @close="addDialogClose" title="添加角色" :visible.sync="addDialogVisible" width="30%">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" class="demo-ruleForm">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName" type="text"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
            <el-button @click="addDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addRole">确 定</el-button>
          </span>
    </el-dialog>
    <!--  编辑角色的对话框  -->
    <el-dialog @close="alterDialogClose" title="修改用户信息" :visible.sync="alterDialogVisible" width="30%">
      <el-form :model="alterForm" ref="alterFormRef" class="demo-ruleForm">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="alterForm.roleName" disabled></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="alterForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
            <el-button @click="alterDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="alterSubmit">确 定</el-button>
          </span>
    </el-dialog>
    <!--  分配权限的对话框  -->
    <el-dialog @close="setDialogClose" title="分配权限" :visible.sync="setDialogVisible" width="30%">
      <!--  引入树形控件  -->
      <el-tree ref="treeRef" node-key="id" :default-checked-keys="defKeys" default-expand-all :data="setList"
               :props="setProps" show-checkbox></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    name: "Roles",
    data() {
      return {
        roleId: '',
        defKeys: [],
        setList: [],
        setDialogVisible: false,
        setProps: {
          label: 'authName',
          children: 'children',
        },
        alterDialogVisible: false,
        alterForm: {
          roleName: '',
          roleDesc: '',
        },
        addDialogVisible: false,
        addForm: {
          roleName: '',
          roleDesc: '',
        },
        /*  验证  */
        addFormRules: {
          roleName: [
            {required: true, message: '请输入角色名称', trigger: 'blur'},
            {min: 2, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur'}
          ],
          roleDesc: [
            {required: false, trigger: 'blur'},
          ],
        },
        rolesList: [],
      }
    },
    created() {
      this.getRolesList();
    },
    methods: {
      /*  确定分配权限*/
      async setSubmit() {
        const arrId = [
          ...this.$refs.treeRef.getCheckedKeys(),
          ...this.$refs.treeRef.getHalfCheckedKeys(),
        ]
        const strId = arrId.join(',');
        const {data: subRes} = await this.$http.post(`roles/${this.roleId}/rights`, {rids: strId})
        if (subRes.meta.status === 200) {
          this.getRolesList();
          this.setDialogVisible = false;
        }
      },
      /*  监听关闭分配权限的对话框  */
      setDialogClose() {
        this.defKeys = [];
      },
      /*  定义递归函数存储 已选中的所有三级节点 */
      getDefKeys(node, arr) {
        if (!node.children) {
          return arr.push(node.id);
        }
        node.children.forEach((item) => {
          this.getDefKeys(item, arr);
        })
      },

      /*  获取分配权限信息  */
      async showSetting(node) {
        /*  保存该角色的id */
        this.roleId = node.id;
        const {data: setRes} = await this.$http.get('rights/tree');
        if (setRes.meta.status === 200) {
          this.setList = setRes.data;
          this.getDefKeys(node, this.defKeys);
          this.setDialogVisible = true;
        } else {
          this.$message.error('分配权限获取失败');
        }
      },
      /*  确定删除权限 */
      deleteById(data, deleteId) {
        this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const {data: deleteRes} = await this.$http.delete(`roles/${data.id}/rights/${deleteId}`);
          if (deleteRes.meta.status === 200) {
            this.$message.success("成功删除权限");
            data.children = deleteRes.data;
          } else {
            this.$message.error("删除权限失败");
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      /*  确定删除角色  */
      deleteRole(deleteId) {
        this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const {data: deleteRes} = await this.$http.delete("roles/" + deleteId);
          if (deleteRes.meta.status === 200) {
            this.$message.success("成功删除角色");
            this.getRolesList();
          } else {
            this.$message.error("删除角色失败");
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      /*  确定编辑角色  */
      alterSubmit() {
        this.$refs.alterFormRef.validate(async (valid) => {
          if (!valid) {
            this.$message.error('编辑失败');
          } else {
            const {data: alterRes} = await this.$http.put('roles/' + this.alterForm.roleId,
              {
                roleDesc:this.alterForm.roleDesc,
                roleName:this.alterForm.roleName
              });
            if (alterRes.meta.status === 200) {
              this.alterDialogVisible = false;
              this.getRolesList();
              this.$message.success('编辑成功');
            } else {
              this.$message.error('编辑失败')
            }

          }
        })
      },
      /*  监听编辑角色的对话框  */
      alterDialogClose() {
        this.$refs.alterFormRef.resetFields();
      },
      /*  获取编辑角色的信息*/
      async alterRole(alterRoleId) {
        const {data: alterRes} = await this.$http.get('roles/' + alterRoleId);
        if (alterRes.meta.status === 200) {
          this.alterDialogVisible = true;
          this.alterForm = alterRes.data;
        } else {
          this.alterDialogVisible = false;
          return this.$message.error('获取角色信息失败');
        }
      },
      /*  确定添加角色  */
      addRole() {
        this.$refs.addFormRef.validate(async (valid) => {
          if (!valid) {
            this.$message.error('提交失败')
          } else {
            const {data: addRes} = await this.$http.post('roles', this.addForm);
            if (addRes.meta.status === 201) {
              this.$message.success('提交成功');
              this.addDialogVisible = false;
              this.getRolesList();
            } else {
              this.$message.error('提交失败');
            }
          }
        })
      },
      /*  监听关闭添加角色对话框 */
      addDialogClose() {
        this.$refs.addFormRef.resetFields();
      },
      /*  请求角色列表数据  */
      async getRolesList() {
        const {data: res} = await this.$http.get('roles');
        if (res.meta.status === 200) {
          this.rolesList = res.data;
          return;
        } else {
          this.$message.error('请求失败');
        }
      }
    }

  }
</script>

<style scoped>
  .el-tag {
    margin: 7px;
  }

  .bdb {
    border-bottom: 1px solid #eee;
  }

  .bdt {
    border-top: 1px solid #eee;
  }

  .center {
    display: flex;
    align-items: center;
  }
</style>
